"use client"
import { useEffect, useState } from "react"
import { Map } from "ol";
import Feature from "ol/Feature";
import { getHeatmapData, HeatmapPoint } from "@/api";
import Point from "ol/geom/Point";
import { fromLonLat } from "ol/proj";
import VectorSource from "ol/source/Vector";
import HeatmapLayer from 'ol/layer/Heatmap.js';

interface Props {
  map: Map;
}

const HeatmapCheckbox: React.FC<Props> = ({ map }) => {

  const [checked, setChecked] = useState(true)
  const [heatmapData, setHeatmapData] = useState<HeatmapPoint[]>([])

  // 热力图数据获取
  useEffect(() => {
    async function main() {
      const data = await getHeatmapData()
      setHeatmapData(data)
    }
    if (checked) {
      main()
    }
  }, [checked]);

  // 轨迹控制
  useEffect(() => {

    if (checked) {

      const vectorSource = new VectorSource();
      heatmapData.forEach(point => {
        const feature = new Feature({
          geometry: new Point(fromLonLat([point.lng, point.lat])),
        });
        feature.set('weight', point.weight); // 设置权重
        vectorSource.addFeature(feature);
      });

      const heatmapLayer = new HeatmapLayer({
        source: vectorSource,
        blur: 15, // 模糊半径
        radius: 10, // 热点半径
        gradient: ['#00f', '#0ff', '#0f0', '#ff0', '#f00'], // 颜色渐变
      });

      map.addLayer(heatmapLayer)


      return () => {
        map.removeLayer(heatmapLayer)
      }
    }
  }, [checked, map, heatmapData]);


  return (
    <input
      className="toggle toggle-sm"
      type="checkbox"
      checked={checked}
      onChange={(e) =>
        setChecked(e.target.checked)
      }
    />
  )
}

export default HeatmapCheckbox